/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package finder.filters;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import finder.IPrimaryFilter;
import finder.ISecondaryFilter;

/**
 *
 * @author Alex
 */
public class RegexFilter implements IPrimaryFilter, ISecondaryFilter
{
    private Pattern regex;
    private int groupNumber = 0;
    private boolean linkable;
    
    public RegexFilter(String pattern, int group, boolean linkable)
    {
        regex = Pattern.compile(pattern);
        this.groupNumber = group;
        this.linkable = linkable;
    }

    @Override
    public List<String> applyFilter(String url, String content) 
    {
        ArrayList<String> list = new ArrayList<>();
        Matcher match = regex.matcher(content);
        while(match.find())
        {
            list.add(match.group(groupNumber));
        }
        return list;
    }
    @Override
    public void applyFilter(List<String> input) 
    {
        for(int i =0; i < input.size();)
        {
            String value = input.get(i);
            Matcher m = regex.matcher(value);
            if (!m.find())
                input.remove(i);
            else
            {//negative group values make a match keep the entire input
               if(groupNumber >= 0)
                   input.set(i, m.group(groupNumber));
               i++;
            }
        }
    }
    @Override
    public boolean producesLinks() 
    {
        return linkable;
    }

    
    
}
